package priorityqueue;

import java.util.Comparator;
import java.util.PriorityQueue;

public class Test1 {
    //最小的k个数
    public int[] smallestK(int[] arr, int k) {
        if (k > arr.length || k <= 0) {
            return new int[0];
        }
        PriorityQueue<Integer> q = new PriorityQueue<Integer>(new Comparator<Integer>() {
            @Override
            public int compare(Integer o1, Integer o2) {
                return o2 - o1;
            }
        });
        for (int i = 0;i < k;i++) {
            q.add(arr[i]);
        }
        int[] result = new int[k];
        for (int i = k;i < arr.length;i++) {
            if (q.peek() > arr[i]) {
                q.poll();
                q.offer(arr[i]);
            }
        }
        for (int i = 0;i < k;i++) {
            result[i] = q.poll();
        }
        return result;
    }
}
